<?php
namespace Home\Controller;
use Think\Controller;
use Think\Log;
use Home\Common\Wechat;

class WxpController extends Controller
{

    public function _initialize ()
    {
        
        $this->valid();
        if (isset($_GET['echostr'])) {
            $this->valid();
        } else {
            $this->responseMsg();
        }
    }

    public function valid ()
    {
        $echoStr = $_GET["echostr"];
        if ($this->checkSignature()) {
            ob_clean();
            echo $echoStr;
            $this->logger("发出请求" . $echoStr);
            exit();
        }
    }

    private function checkSignature ()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = 'zhangyida';
        $this->logger(
                "传入的值" . "##########" . $timestamp . '===================' .
                         $nonce);
        $tmpArr = array(
                $token,
                $timestamp,
                $nonce
        );
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        $this->logger(
                TOKEN . "##########" . $tmpStr . '===================' .
                         $signature);
        // Log::write("微信验证------".$signature, "ERR");
        // Log::write("微信验证======".$tmpStr, "ERR");
        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    public function responseMsg ()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        Log::write("微信验证--".$postStr, "ERR");
        if (! empty($postStr)) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', 
                    LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
            if ($keyword == "?" || $keyword == "？") {
                $msgType = "text";
                $contentStr = date("Y-m-d H:i:s", time());
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, 
                        $time, $msgType, $contentStr);
                echo $resultStr;
            }
        } else {
            echo "";
            exit();
        }
    }

    function traceHttp ()
    {
        $this->logger(
                "\n\nREMOTE_ADDR:" . $_SERVER["REMOTE_ADDR"] .
                         (strstr($_SERVER["REMOTE_ADDR"], '101.226') ? " FROM WeiXin" : "Unknown IP"));
        $this->logger("QUERY_STRING:" . $_SERVER["QUERY_STRING"]);
    }

    function logger ($log_content)
    {
        if (isset($_SERVER['HTTP_APPNAME'])) { // SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        } else { // LOCAL
            $max_size = 500000;
            $log_filename = "log.xml";
            if (file_exists($log_filename) and
                     (abs(filesize($log_filename)) > $max_size)) {
                unlink($log_filename);
            }
            file_put_contents($log_filename, 
                    date('Y-m-d H:i:s') . $log_content . "\r\n", FILE_APPEND);
        }
    }

    public function index ()
    {
       
        // 配置文件
        // AppID(应用ID)
        $appid = C('appid');
        // 微信后台填写的TOKEN
        $token = C('token');
        // 消息加密KEY（EncodingAESKey）
        $crypt = C('encodingaeskey');
     
        // 加载微信sdk
        $wechat = new Wechat($token, $appid, $crypt);
        // 获得微信请求消息
        $data = $wechat->request();
        
        // $openid = $data['FromUserName'];
        // if ($data['Event'] == "subscribe") {
        //     $content="多推客 | 朋友圈推广，从这里开始\n\n全国各地千万“推客”一起分享，\n刷屏朋友圈。\n\n按效果付费，\n低至0.1元/人真实阅读，330元起投。\n\n谁分享、谁阅读，\n数据实时透明，无效阅读不计费。";
        //     $res=$wechat->replyText2($content); 
        // }
        // // 根据不同的提示给出不同的信息
        // $type = $data['MsgType'];
        // if ($type == 'event') {
        //     $keyword = $data['Event'];
        //     $keyEventType=$data['EventKey'];
        //     if($keyword=="LOCATION"){
        //         // 更新用户的地理位置
        //         $locationArr['Npostion']=$data['Latitude'];
        //         $locationArr['Spostion']=$data['Longitude'];
        //         M('user')->where(array('userOpenId'=>$openid))->setField('userLocation',json_encode($locationArr));
        //     }
        //     if($keyEventType=="cooperate")
        //     {
        //         $content="请拨打商务热线：4000057661";
        //         $wechat->replyText($content);
        //     }
        //     if ($keyEventType=="subscribe") {
                
        //     }
        // } else if ($type == 'text') {
        //     $keyword = $data['Content'];
        //     if($keyword=="1")
        //     {
        //         $content="<a href='http://www.baidu.com'>请拨打商务热线</a>";
        //         $wechat->replyText($content);
        //     }
            
        // } else if ($type == 'image'){
            
        // }
    }

    public function createMenu ()
    {
        
        // $appid = C('appid');
        $appid = 'wx75b0316b2ba4fb1a';
        // $appsecret = C('appsecret');
  
        // $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";     
        // $output = http_get($url);
        // $jsoninfo = json_decode($output, true);
        // $access_token = $jsoninfo["access_token"];
        // $appid = 'wx8fd7fb6972ff88e1';
        $myuserRes=M('wx_tpfauth_md')->where(array('appid'=>$appid))->field('actid')->find();
                        $wxActTpfauthService = new \Home\Server\WxActTpfauthService();
        $access_token=$wxActTpfauthService->getTokenByActIdFromDB($myuserRes['actid'], $appid);
        $access_token = $access_token['authorizerAccessToken'];
        
       
     //    $jsonmenu = '{ "button":[

     //   {  
     //      "type":"click",
     //      "name":"最新任务",
     //      "key":"DTK_GET_TASK"
     //    },
     //    {
     //       "name":"任务广场",
     //       "type":"view",
     //       "url":"http://wx.duotuike.com/"
     //   },
     //    {
     //       "name":"提现",
     //       "type":"view",
     //       "url":"http://wx.duotuike.com/Home/Share/moneyGet"
     //   }]
     // }';
     $jsonmenu = '{ "button":[
        {
           "name":"兑换商城",
           "type":"view",
           "url":"http://yans.snsads9.top/pj/mall/toIndex"
       }]
     }';
        //$jsonmenu='{"button":}';
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" .
                 $access_token;
//         $make_menu_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" . $access_token;
        $result = http_post($url, $jsonmenu);
        //$result = http_post($url);
        var_dump($result);
    }
}

?>